//
//  Pie.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 10.04.25.
//

import SwiftUI

struct KoiPie: View {

    @Binding var slices: [(value:Double, color:Color)]

    var body: some View {
        Canvas { context, size in
            let total = slices.reduce(0) { $0 + $1.0 }
            context.translateBy(x: size.width * 0.5, y: size.height * 0.5)
            var pieContext = context
            pieContext.rotate(by: .degrees(-90))
            let radius = min(size.width, size.height) * 0.48
            var startAngle = Angle.zero
            for (value, color) in slices {
                let angle = Angle(degrees: 360 * (value / total))
                let endAngle = startAngle + angle
                let path = Path { p in
                    p.move(to: .zero)
                    p.addArc(center: .zero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
                    p.closeSubpath()
                }
                pieContext.fill(path, with: .color(color))

                startAngle = endAngle
            }
        }
        .aspectRatio(1, contentMode: .fit)
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var data = [
        (value:0.2, color:Color.red),
        (value:0.3, color:Color.orange),
        (value:0.4, color:Color.yellow),
        (value:0.1, color:Color.green),
        (value:0.15, color:Color.blue),
        (value:0.2, color:Color.indigo),
        (value:0.2, color:Color.purple)
    ]
    KoiPie(slices: $data)
}
